package cn.tedu.egmvc4.controller;

import cn.tedu.egmvc4.base.response.JsonResult;
import cn.tedu.egmvc4.base.response.StatusCode;
import cn.tedu.egmvc4.mapper.UserMapper;
import cn.tedu.egmvc4.pojo.dto.UserAddParam;
import cn.tedu.egmvc4.pojo.dto.UserUpdateParam;
import cn.tedu.egmvc4.pojo.entity.User;
import cn.tedu.egmvc4.pojo.vo.UserListVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/v1/user/")
@Api(tags = "用户模块管理")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("add")
    @ApiOperation("添加用户")
    @ApiOperationSupport(order = 10)
    public JsonResult add(UserAddParam userAddParam) {
        log.debug(userAddParam + "");
        User user = new User();
        BeanUtils.copyProperties(userAddParam, user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        int num = userMapper.insertUser(user);
        return num > 0 ? JsonResult.ok() : new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @GetMapping("list")
    @ApiOperation("用户列表")
    @ApiOperationSupport(order = 20)
    public JsonResult list() {
        List<UserListVO> userList = userMapper.userList();
        return JsonResult.ok(userList);
    }

    @PostMapping("del")
    @ApiOperation("删除用户")
    @ApiOperationSupport(order = 30)
    @ApiImplicitParam(name = "id", value = "用户编号", dataType = "Long", required = true)
    public JsonResult del(Long id) {
        if (id < 0) {
            throw new IllegalArgumentException("id值非法！！！");
        }
        log.debug("id:" + id);
        int num = userMapper.deleteUserById(id);
        return num > 0 ? JsonResult.ok() : new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @PostMapping("update")
    @ApiOperation("修改用户")
    @ApiOperationSupport(order = 40)
    public JsonResult update(@ApiIgnore UserUpdateParam userUpdateParam) {
        log.debug("" + userUpdateParam);
        User user = new User();
        BeanUtils.copyProperties(userUpdateParam, user);
        user.setUpdateTime(new Date());
        int num = userMapper.updateUserById(user);
        return num > 0 ? JsonResult.ok() : new JsonResult(StatusCode.OPERATION_FAILED);
    }
}
